<template>
  <j-modal
    :title="title"
    :width="520"
    :visible="visible"
    :footer="null"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <div class="qr-wrap">
      <QrCode :value="qrUrl" :width="240" ref="qrRef" @done="onQrDone" />
      <div class="link-box">
        <a-input v-model:value="qrUrl" readonly />
        <a-space>
          <!--          <a-button size="small" @click="copyUrl">复制链接</a-button>-->
          <a-button type="primary" size="big" @click="downloadQr">下载二维码</a-button>
        </a-space>
        <br/>
        <a-space>
          <a-button type="primary" size="big" @click="sendUrl">发送链接至钉钉</a-button>
        </a-space>
      </div>
    </div>
  </j-modal>
</template>

<script lang="ts" setup>
import { ref, defineExpose } from 'vue';
import JModal from '/@/components/Modal/src/JModal/JModal.vue';
import QrCode from '/@/components/Qrcode/src/Qrcode.vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { defHttp } from '/@/utils/http/axios';

const { createMessage } = useMessage();
const title = ref('生成试卷二维码');
const visible = ref(false);
const qrUrl = ref('');
const qrRef = ref<any>(null);
const currentRecord = ref<Recordable | null>(null);

// 钉钉唤起Url（path 需 encode）
const BASE_URL = 'https://applink.dingtalk.com/page/h5_app_open';
const APP_ID = '3954441815';
const CORP_ID = 'ding60ca55316ff60640f5bf40eda33b7ba0';
const APP_TYPE = '2';

function buildUrl(mainId: string) {
  const pathRaw = `/quiz.html?pid=${mainId}`;
  const pathEncoded = encodeURIComponent(pathRaw);
  return `${BASE_URL}?appId=${APP_ID}&corpId=${CORP_ID}&appType=${APP_TYPE}&path=${pathEncoded}`;
}

function open(record: Recordable) {
  const id = record?.id;
  if (!id) {
    createMessage.warning('缺少试题ID');
    return;
  }
  currentRecord.value = record;
  qrUrl.value = buildUrl(id);
  visible.value = true;
}

function handleCancel() {
  visible.value = false;
}

function copyUrl() {
  navigator.clipboard?.writeText(qrUrl.value).then(() => {
    createMessage.success('已复制链接');
  });
}

function downloadQr() {
  qrRef.value?.download?.('试卷二维码.png');
}

function sendUrl() {
  const id = currentRecord.value?.id;
  const commonParams = {
    id: id,
    qrUrl:qrUrl.value
  };
  defHttp.get({
    url: '/hr/dtQuestionResult/robot/send',
    params: commonParams,
  });
}

function onQrDone() {}

defineExpose({ open });
</script>

<style lang="less" scoped>
.qr-wrap {
  display: flex;
  gap: 16px;
  align-items: center;
}
.link-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
</style>
